<template>
  <div class="app-container">
    <el-form ref="uf" label-width="120px" :model="user" :rules="rules">
      <el-row>
        <el-col :span="16" :xs="24">
          <el-row>
            <el-col :span="12" :xs="24">
              <el-form-item label="登录名" prop="username" class="is-required">
                <el-input v-model.trim="user.username" clearable />
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model.trim="user.sex" size="small">
                  <el-radio-button :label="1">男</el-radio-button>
                  <el-radio-button :label="2">女</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item prop="email" label="邮箱">
                <el-input v-model.trim="user.email" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12" :xs="24">
              <el-form-item label="姓名" prop="realName" class="is-required">
                <el-input v-model.trim="user.realName" clearable />
              </el-form-item>
              <el-form-item label="状态" prop="locked">
                <el-switch v-model.trim="locked" active-color="#ff4949" inactive-color="#409EFF" class="mr5" @change="changeLock" />
                <span>{{ locked == 1 ?'锁定' : '正常' }}</span>
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model.trim="user.phone" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider />
          <el-row class="w100">
            <el-form-item v-loading="load" label="所在组织结构">
              <el-tag
                v-for="(o,i) in parent"
                :key="i"
                :type="o.orgType===3 ? 'danger':''"
                closable
                class="inline-block m5"
                @close="removeTag(i)"
              >{{ o.orgName }}</el-tag>
              <el-divider v-if="parent.length > 0" direction="vertical" />
              <el-button size="small" icon="el-icon-plus" @click="showOrgTag = true">添加</el-button>
              <el-button v-show="parent.length > 0" size="small" icon="el-icon-close" @click="parent = []">清空</el-button>
            </el-form-item>
          </el-row>
          <el-row class="w100">
            <el-form-item label="行政上级" v-loading="load2">
              <user-view v-model="superior" :multi="false" ref="userSelect" @addTag="saveSuperior"/>
            </el-form-item>
          </el-row>
        </el-col>
        <el-col :span="8" style="padding-left: -20px" class="center" :xs="24">
          <el-upload
            ref="upload"
            :data="user"
            :headers="token"
            :accept="accept"
            :auto-upload="false"
            class="avatar-uploader"
            :action="serverPath + '/sys/user/save'"
            :show-file-list="false"
            :on-change="handleAvatarSuccess"
            :on-success="submitSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="user.avatar" :src="user.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
          <!--<el-button type="primary" icon="el-icon-upload" class="mt5">
            上传头像
          </el-button>-->
        </el-col>
      </el-row>
    </el-form>
    <el-footer class="w-footer">
      <el-button size="small" type="primary" icon="iconfont icon-baocunwendang" :disabled="load2||load" :loading="saveLoad" @click="saveUser">保 存</el-button>
      <el-button size="small" icon="el-icon-close" @click="closeTab">关 闭</el-button>
    </el-footer>
    <el-dialog
      title="选择组织结构"
      :visible.sync="showOrgTag"
      :append-to-body="true"
      :close-on-click-modal="false"
      width="800px"
      @open="openTag"
    >
      <component :is="orgTag" ref="tag" />
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="addTag">保 存</el-button>
        <el-button size="small" @click="showOrgTag = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>

</template>
<script>

import { getSaveUser, getUser, getUserByOrgId, listParent } from '@/api/user'
import { validator } from '@/utils/form'
import { getToken } from '@/utils/auth'
import UserView from '@/components/tag/userView'

const basePath = process.env.VUE_APP_BASE_API
export default {
  name: 'UserEdit',
  components: { UserView },
  data() {
    return {
      load: false,
      load2: false,
      saveLoad: false,
      locked: false,
      showOrgTag: false,
      accept: '.jpg,.jpeg,.png,.gif',
      serverPath: basePath === '/' ? '' : basePath,
      superior:[],
      user: {
        userId: 0,
        username: '',
        realName: '',
        avatar: '',
        head: null,
        superior: null,
        sex: 1,
        locked: 0,
        email: '', phone: '', newOrgIdList: []
      },
      parent: []
    }
  },
  computed: {
    orgTag() {
      return require('/src/components/tag/org-tag').default
    },
    token() {
      return {
        appToken: getToken()
      }
    },
    rules() {
      return {
        username: [
          { validator: validator('notBlank'), message: '请输入登录名', trigger: ['blur', 'change'] },
          { validator: validator('maxLen', 30), message: '登录名长度最大30', trigger: ['blur', 'change'] }
        ],
        realName: [
          { validator: validator('notBlank'), message: '请输入姓名', trigger: ['blur', 'change'] },
          { validator: validator('maxLen', 40), message: '姓名长度最大40', trigger: ['blur', 'change'] }
        ],
        email: [
          { validator: validator('email_empty'), message: '请输入正确的邮箱', trigger: ['blur', 'change'] },
          { validator: validator('maxLen', 50), message: '邮箱长度最大50', trigger: ['blur', 'change'] }
        ],
        phone: [
          { validator: validator('phone_empty'), message: '手机号格式不正确', trigger: ['blur', 'change'] },
          { validator: validator('maxLen', 20), message: '手机号长度最大20', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  mounted() {
    const userId = this.$route.params.userId
    if (userId > 0) {
      this.load = true
      getUser(userId).then((res) => {
        this.user = res.data
        this.locked = this.user.locked !== 0
        listParent(this.user.orgId).then((d) => {
          this.parent = d.data
          const l = []
          for (let i = 0; i < this.parent.length; i++) {
            l.push(this.parent[i].orgId)
          }
          this.user.newOrgIdList = l
        }).finally(()=>this.load = false)
        if(this.user.superior != null && this.user.superior > 0){
          this.load2 = true
          getUser(this.user.superior).then((r)=>{
            if(r.data){
              this.superior = [r.data]
            }
          }).finally(()=>this.load2 = false)
        }
      })
    }
  },
  methods: {
    saveSuperior(user,userIds) {
      this.user.superior=userIds[0]
    },
    submitSuccess(file) {
      this.saveLoad = false
      this.$message.success('保存成功')
    },
    handleAvatarSuccess(file) {
      this.user.avatar = URL.createObjectURL(file.raw)
      console.log(file.raw)
      this.user.head = file.raw
    },
    beforeAvatarUpload(file) {
      /* const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M */
      return true
    },
    removeTag(i) {
      this.parent.splice(i, 1)
    },
    addTag() {
      const p = this.$refs.tag.get()
      if (p.length === 0) {
        this.$message.warning('请选择组织结构')
        return
      }
      // 去重
      const ids = []
      for (let i = 0; i < this.parent.length; i++) {
        ids.push(this.parent[i].orgId)
      }
      for (let i = 0; i < p.length; i++) {
        if (ids.indexOf(p[i].orgId) === -1) {
          this.parent.push(p[i])
        }
      }
      this.showOrgTag = false
    },
    closeTab() {
      this.$tab.closePageBack()
    },
    openTag() {
      this.$nextTick(() => {
        // this.$refs.tag.clear()
        this.$refs.tag.query()
      })
    },
    saveUser() {
      this.$refs['uf'].validate((valid) => {
        if (valid) {
          const newOrgIdList = []
          for (let i = 0; i < this.parent.length; i++) {
            newOrgIdList.push(this.parent[i].orgId)
          }
          if(this.superior.length > 0){
            this.user.superior = this.superior[0].userId
          }else{
            this.user.superior = 0
          }
          this.user.newOrgIdList = newOrgIdList
          this.saveLoad = true
          console.log(this.user)
          if (this.user.head == null) {
            getSaveUser(this.user).then((d) => {
              if (this.user.userId === 0) {
                this.user.userId = d.data
              }
              this.saveLoad = false
              this.$message.success('保存成功')
            }).catch(() => {
              this.saveLoad = false
            })
          } else {
            this.$refs.upload.submit()
          }
        }
      })
    },
    changeLock(v) {
      this.user.locked = v ? 1 : 0
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
::v-deep .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
